package org.dromara.school.service.impl;

import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.school.domain.BindingSchools;
import org.dromara.school.domain.Classes;
import org.dromara.school.domain.bo.SchoolClassesTreeNodeBo;
import org.dromara.school.domain.bo.SchoolTreeNodeBo;
import org.dromara.school.domain.vo.ClassesVo;
import org.dromara.school.mapper.BindingSchoolsMapper;
import org.dromara.school.service.IBindingSchoolsService;
import org.dromara.system.domain.SysTenant;
import org.dromara.system.domain.SysuserBindingSchools;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.mapper.SysuserBindingSchoolsMapper;
import org.dromara.system.service.ISysTenantService;
import org.dromara.system.service.ISysuserBindingSchoolsService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.dromara.school.domain.bo.CampusBo;
import org.dromara.school.domain.vo.CampusVo;
import org.dromara.school.domain.Campus;
import org.dromara.school.mapper.CampusMapper;
import org.dromara.school.service.ICampusService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 校区管理Service业务层处理
 *
 * @author gjb
 * @date 2025-05-28
 */
@RequiredArgsConstructor
@Service
public class CampusServiceImpl implements ICampusService {

    private final CampusMapper baseMapper;

    private final SysuserBindingSchoolsMapper schoolBindingSchoolsMapper;

    private final ISysTenantService tenantService;

    private final ISysuserBindingSchoolsService bindingSchoolsService;
    /**
     * 查询校区管理
     */
    @Override
    public CampusVo queryById(Long campusId){
        return baseMapper.selectVoById(campusId);
    }

    /**
     * 查询校区管理列表
     */
    @Override
    public TableDataInfo<CampusVo> queryPageList(CampusBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Campus> lqw = buildQueryWrapper(bo);
        Page<CampusVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询校区管理列表
     */
    @Override
    public List<CampusVo> queryList(CampusBo bo) {
        LambdaQueryWrapper<Campus> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Campus> buildQueryWrapper(CampusBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Campus> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getCampusName()), Campus::getCampusName, bo.getCampusName());
        lqw.like(StringUtils.isNotBlank(bo.getCampusShortName()), Campus::getCampusShortName, bo.getCampusShortName());
        lqw.eq(StringUtils.isNotBlank(bo.getCampusAddress()), Campus::getCampusAddress, bo.getCampusAddress());
        lqw.eq(bo.getCampusNature() != null, Campus::getCampusNature, bo.getCampusNature());
        lqw.eq(StringUtils.isNotBlank(bo.getPostcode()), Campus::getPostcode, bo.getPostcode());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), Campus::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getFax()), Campus::getFax, bo.getFax());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), Campus::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getCampusManager()), Campus::getCampusManager, bo.getCampusManager());
        lqw.eq(StringUtils.isNotBlank(bo.getCampusManagerPhone()), Campus::getCampusManagerPhone, bo.getCampusManagerPhone());
        return lqw;
    }

    /**
     * 新增校区管理
     */
    @Override
    public Boolean insertByBo(CampusBo bo) {
        Campus add = MapstructUtils.convert(bo, Campus.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCampusId(add.getCampusId());
        }
        return flag;
    }

    /**
     * 修改校区管理
     */
    @Override
    public Boolean updateByBo(CampusBo bo) {
        Campus update = MapstructUtils.convert(bo, Campus.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Campus entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除校区管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<CampusVo> findCampusByTenantId() {

//        SELECT sc.*
//        FROM school_campus sc
//        JOIN school_binding_schools sbs ON sc.campus_id = sbs.school_campus_id
//        WHERE sbs.tenant_id = '000000'
//        AND sbs.teacher_id = '1933448024981245954'

//        MPJLambdaWrapper<Campus> mpj = JoinWrappers.lambda(Campus.class)
//            .selectAll(Campus.class);

        LoginUser loginUser = LoginHelper.getLoginUser();
        UserType userType = UserType.getUserType(loginUser.getUserType());

        List<CampusVo> list = null;
        MPJLambdaWrapper<SysuserBindingSchools> mpj= new MPJLambdaWrapper<SysuserBindingSchools>();

        switch (userType) {
            case SYS_USER:
                TenantHelper.enableIgnore();
              list = this.baseMapper.selectVoList();
                TenantHelper.disableIgnore();
                break;
            case SCHOOLADMIN:
                MPJLambdaWrapper<Campus> cmpj= new MPJLambdaWrapper<Campus>();
                 mpj.selectAll(Campus.class);
                //获取到所有绑定的校区
                cmpj.eq( Campus::getTenantId,TenantHelper.getTenantId());
               list = this.baseMapper.selectVoList(cmpj);
                break;
            case TEACHER:

               mpj.selectAll(Campus.class);
                //获取到所有绑定的校区
               mpj.leftJoin(Campus.class, Campus::getCampusId, SysuserBindingSchools::getSchoolCampusId)
                .eq(SysuserBindingSchools::getTenantId, TenantHelper.getTenantId())
                .eq(SysuserBindingSchools::getUserId, loginUser.getTeacherId());
                list = schoolBindingSchoolsMapper.selectJoinList(
                    CampusVo.class,mpj);
                break;
            default:
                return null;
        }





        return list;
    }
//    @Cacheable(value="schoolCampus",key="#campusId",unless="#result == null")
    @Override
    public Campus selectSchoolCampusById(Long campusId) {
       return baseMapper.selectById(campusId);
    }

    @Override
    public Campus findSchoolCampus(Campus campus) {
        //拼装查询条件
        LambdaQueryWrapper<Campus> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotNull(campus.getCampusName())) {
            queryWrapper.eq(StringUtils.isNotEmpty(campus.getCampusName()), Campus::getCampusName, campus.getCampusName());
            queryWrapper.eq(StringUtils.isNotEmpty(campus.getTenantId()), Campus::getTenantId, campus.getTenantId());
            return baseMapper.selectOne(queryWrapper);
        }
        return null;
    }

    @Override
    public List<Campus> findCampusList(Campus campus) {

        LambdaQueryWrapper<Campus> queryWrapper = new LambdaQueryWrapper<>();

        TenantHelper.setDynamic(campus.getTenantId());//设置租户id
//        queryWrapper.eq(StringUtils.isNotEmpty(campus.getTenantId()), Campus::getTenantId, campus.getTenantId());
        return baseMapper.selectList(queryWrapper);


//        LambdaQueryWrapper<Campus> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询
//        if (campus != null) {
//            System.out.println(campus.getTenantId());
//            queryWrapper.eq(StringUtils.isNotNull(campus.getTenantId()), Campus::getTenantId, campus.getTenantId());
////            queryWrapper.like(StringUtils.isNotNull(campus.getCampusName()), Campus::getCampusName, campus.getCampusName());
////            queryWrapper.like(StringUtils.isNotNull(campus.getCampusShortName()), Campus::getCampusShortName, campus.getCampusShortName());
////            queryWrapper.like(StringUtils.isNotNull(campus.getCampusAddress()), Campus::getCampusAddress, campus.getCampusAddress());
//        }
//        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Campus> findSchoolCampusNamesByIds(List<Long> campusids) {
        LambdaQueryWrapper<Campus> lqw = new LambdaQueryWrapper<Campus>();
        lqw.select(Campus::getCampusId, Campus::getCampusName).in(Campus::getCampusId, campusids);

        return baseMapper.selectList(lqw);
    }


    @Override
    public List<SchoolTreeNodeBo> getSchoolTreeNode() {

        LoginUser loginUser = LoginHelper.getLoginUser();
        UserType userType = UserType.getUserType(loginUser.getUserType());
        //根节点
        List<SchoolTreeNodeBo> listfirstNode = new ArrayList<>();
        //租户 （学校）
        List<SysTenant> schoolList = new ArrayList<>();

//        String tenantId = loginUser.getTenantId();

        SysTenantVo sysTenantVo = this.tenantService.queryByTenantId(TenantHelper.getTenantId());

        List<SysuserBindingSchools> bindingSchools = null;

        switch (userType) {
            case SYS_USER:
                //系统用户  获取到所有的学校
                schoolList = this.tenantService.findTenantList();

                for (SysTenant school : schoolList) {
                    SchoolTreeNodeBo firstNode = new SchoolTreeNodeBo();
                    firstNode.setLabel(school.getCompanyName());//tree 返回学校名称
                    firstNode.setSchoolId(school.getId());
                    Campus schoolCampus = new Campus();
                    schoolCampus.setTenantId(school.getTenantId());
                    //遍历所有学校拿到校区
                    List<Campus> schoolCampusList = this.findCampusList(schoolCampus);
                    schoolNodes(listfirstNode, firstNode, schoolCampusList);

                }
                break;
            case SCHOOLADMIN:
                //如果是管理员账号 可以查看所有校区
                SchoolTreeNodeBo firstNode = new SchoolTreeNodeBo();
                //获取到登录用户tranentId
                firstNode.setLabel(sysTenantVo.getCompanyName());//tree 返回学校名称
                firstNode.setSchoolId(sysTenantVo.getId());
                Campus schoolCampus = new Campus();
                schoolCampus.setTenantId(sysTenantVo.getTenantId());
                //遍历所有学校拿到校区
                List<Campus> schoolCampusList = this.findCampusList(schoolCampus);
                schoolNodes(listfirstNode, firstNode, schoolCampusList);
//
//                bindingSchools = this.bindingSchoolsService.findByTeacherId(loginUser.getTeacherId());
//                List<Campus> schoolCampusNamesByIds =null;
//
//              if(bindingSchools.size()>0){
//                  List<Long> campusids = bindingSchools.stream()
//                      .map(BindingSchools::getSchoolCampusId)
//                      .collect(Collectors.toList());
//                  schoolCampusNamesByIds = this.findSchoolCampusNamesByIds(campusids);
//              }
//
//                SchoolTreeNodeBo firstNode = new SchoolTreeNodeBo();
//                firstNode.setLabel(sysTenantVo.getCompanyName());//tree 返回学校名称
//                firstNode.setSchoolId(sysTenantVo.getId());
//                schoolNodes(listfirstNode, firstNode, schoolCampusNamesByIds);




                break;
            case TEACHER:
                // List<Long> teachercampusids = Arrays.asList(loginUser.getSysUser().getSchoolCampusIds().split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
                // List<String> schoolCampus = Arrays.asList(loginUser.getSysUser().getSchoolCampusName().split(",")).stream().collect(Collectors.toList());

                bindingSchools = this.bindingSchoolsService.findByUserId(loginUser.getUserId());
                List<Long> teachercampusids = bindingSchools.stream()
                    .map(SysuserBindingSchools::getSchoolCampusId)
                    .collect(Collectors.toList());
                SchoolTreeNodeBo teacherfirstNode = new SchoolTreeNodeBo();
                teacherfirstNode.setLabel(sysTenantVo.getCompanyName());//tree 返回学校名称
                teacherfirstNode.setSchoolId(sysTenantVo.getId());
                List<Campus> teacherschoolCampusNamesByIds = this.findSchoolCampusNamesByIds(teachercampusids);
                schoolNodes(listfirstNode, teacherfirstNode, teacherschoolCampusNamesByIds);
                break;
            default:
                return null;
        }


        return listfirstNode;
    }




    private void schoolNodes(List<SchoolTreeNodeBo> listfirstNode, SchoolTreeNodeBo firstNode, List<Campus> schoolCampusList) {
        List<SchoolTreeNodeBo> listsecondNode = new ArrayList<>();
        if(schoolCampusList!=null){
            for (Campus campus : schoolCampusList) {
                SchoolTreeNodeBo secondNode = new SchoolTreeNodeBo();
                secondNode.setLabel(campus.getCampusName());//tree 返回学校名称
                secondNode.setSchoolCampusId(campus.getCampusId());
                secondNode.setTenantId(campus.getTenantId());
                listsecondNode.add(secondNode);// 二级节点添加到集合中    ##
                //通过校区id拿到所有年级
            }
        }
        firstNode.setChildren(listsecondNode);//一级节点添加子集
        listfirstNode.add(firstNode);//一级节点添加到集合中         #####
    }





}
